package org.zn.etl.jdbc;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

import javax.sql.DataSource;

import org.zn.datax.common.entity.ColumnInfo;
import org.zn.etl.job.handler.StateOfRWBuffer;

import com.alibaba.druid.util.JdbcUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class QueryHelper {
	
	
	public static StateOfRWBuffer<Map<String, Object>> queryStateOfRWBuffer(DataSource sSource,String sql, int fetchSize) throws SQLException{
		
		Connection conn= sSource.getConnection();
		ResultSet  rs=null;
		Statement stat=null;
		StateOfRWBuffer<Map<String, Object>>  buffer=null;
		try {		
			
		stat=conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY);
		stat.setQueryTimeout(3600*24);	
		stat.setFetchSize(fetchSize);
		log.debug("begin queryMapList:{}",sql);
		
		rs=stat.executeQuery(sql);
		
		log.debug("finish executeQuery");
		
	
		buffer=ResultSetTools.readToStateOfRWBuffer(rs,conn,stat,fetchSize);
		
		log.debug("frist retrun  buffer");
	
		} catch (Exception e) {
			log.error("queryMapList error,sSource:{} ,sql:{}",sSource,sql,e);
		}
		
		return buffer;
		
	}
	

	/**
	 * res Map key igone 大小写 toLowerCase
	 * @param sSource
	 * @param sql
	 * @return
	 * @throws SQLException
	 */
	public static List<Map<String, Object>> queryMapList(DataSource sSource,String sql) throws SQLException{
		
		Connection conn= sSource.getConnection();
		ResultSet  rs=null;
		Statement stat=null;
		List<Map<String, Object>>  list=null;
		try {		
			
		stat=conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY);
		stat.setQueryTimeout(3600*24);	
		stat.setFetchSize(200);
		log.debug("begin queryMapList:{}",sql);
		
		rs=stat.executeQuery(sql);
		
		log.debug("finish executeQuery");
		
		//CopyOnWriteArrayList<E>
		
		list=ResultSetTools.toMapReslt(rs);
		
		log.debug("finish ResultSet:{}",list.size());
	
		} catch (Exception e) {
			log.error("queryMapList error,sSource:{} ,sql:{}",sSource,sql,e);
		}finally {	
			
			JdbcUtils.close(rs);
			JdbcUtils.close(stat);
			JdbcUtils.close(conn);
		}
		
		return list;
		
	}
	
	public static Map<String, ColumnInfo> queryMeta(DataSource sSource,String sql) throws SQLException{
		
		Connection conn= sSource.getConnection();
		ResultSet  rs=null;
		try {
		rs=conn.createStatement().executeQuery(sql);		
		Map<String, ColumnInfo> scMap=ResultSetTools.columnMetaData(rs);
		JdbcUtils.close(rs);
		return scMap;
		} catch (Exception e) {
			log.error("queryMeta error,sSource:{} ,sql:{}",sSource,sql,e);
		}finally {
			JdbcUtils.close(conn);
		}
		return null;
		
	}
	
}
